package com.live.shop.home.setting;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.live.shop.BaseActivity;
import com.live.shop.R;
import com.live.shop.model.PermissionModel;
import com.live.shop.tool.GetUtil;
import com.live.shop.tool.StatusBarUtils;
import com.live.shop.view.ToastUtils;

import java.util.ArrayList;
import java.util.List;

public class PermissionActivity extends BaseActivity {
    ImageButton permission_back;
    RecyclerView permission_recyclerview;
    private List<PermissionModel> list = new ArrayList<>();
    private MyAdapter adapter;
    boolean isGotoGetPermission = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_permission);
        StatusBarUtils.setDarkStatusWhite(this,R.color.white);

        permission_back = findViewById(R.id.permission_back);
        permission_recyclerview = findViewById(R.id.permission_recyclerview);

        permission_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        setData();
    }

    public void setData(){
        list.clear();
        //ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED
        list.add(new PermissionModel("悬浮窗", new String[]{Manifest.permission.SYSTEM_ALERT_WINDOW},
                "打开悬浮窗，一键操作直播话术和回复的状态开关。", false));
        list.add(new PermissionModel("应用内安装其他应用", new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES},
                "本应用版本更新安装。", false));
        list.add(new PermissionModel("无障碍", new String[]{Manifest.permission.BIND_ACCESSIBILITY_SERVICE},
                "获取自己开播平台的评论。", false));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            list.add(new PermissionModel("读写(高版本)", new String[]{Manifest.permission.MANAGE_EXTERNAL_STORAGE},
                    "读取本地照片,写入生成的音频及下载新版本应用到本地", false));
        }else{
            list.add(new PermissionModel("读写",new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    "读取本地照片,写入生成的音频及下载新版本应用到本地。", false));
        }
        list.add(new PermissionModel("摄像头", new String[]{Manifest.permission.CAMERA},
                "获取摄像头进行实景拍摄。", false));
        list.add(new PermissionModel("访问网络", new String[]{Manifest.permission.INTERNET},
                "与服务端进行数据通讯。", false));
        list.add(new PermissionModel("查看网络状态", new String[]{Manifest.permission.ACCESS_NETWORK_STATE},
                "查看网络状态。", false));
        list.add(new PermissionModel("查看WLAN状态", new String[]{Manifest.permission.ACCESS_WIFI_STATE},
                "查看WLAN状态。", false));
        list.add(new PermissionModel("震动", new String[]{Manifest.permission.VIBRATE},
                "操作提醒进行震动。", false));
        list.add(new PermissionModel("麦克风", new String[]{Manifest.permission.RECORD_AUDIO},
                "使用麦克风进行音频录制。", false));
        list.add(new PermissionModel("控制屏幕锁定", new String[]{Manifest.permission.WAKE_LOCK},
                "允许应用获取唤醒锁，无人直播回复和话术时，用于控制屏幕锁定。", false));

        for(int i = 0 ; i < list.size() ; i++){
            for(String permission : list.get(i).getPermission()){
                switch (i){
                    case 0://悬浮窗
                        if(Settings.canDrawOverlays(getApplicationContext())){
                            list.get(i).setIsget(true);
                        }else{
                            list.get(i).setIsget(false);
                        }
                        break;
                    case 1://应用内安装其他应用
                        if(getPackageManager().canRequestPackageInstalls()){
                            list.get(i).setIsget(true);
                        }else{
                            list.get(i).setIsget(false);
                        }
                        break;
                    case 2://无障碍
                        if(GetUtil.isAccessibilitySettingsOn(getApplicationContext())){
                            list.get(i).setIsget(true);
                        }else{
                            list.get(i).setIsget(false);
                        }
                        break;
                    case 3://读写
                        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
                            //高版本
                            if(Environment.isExternalStorageManager()){
                                list.get(i).setIsget(true);
                            }else{
                                list.get(i).setIsget(false);
                            }
                        }else{
                            //低版本
                            if(ContextCompat.checkSelfPermission(getApplicationContext(), permission) != PackageManager.PERMISSION_GRANTED){
                                list.get(i).setIsget(false);
                            }else{
                                list.get(i).setIsget(true);
                            }
                        }
                        break;
                    default:
                        if(ContextCompat.checkSelfPermission(getApplicationContext(), permission) != PackageManager.PERMISSION_GRANTED){
                            list.get(i).setIsget(false);
                        }else{
                            list.get(i).setIsget(true);
                        }
                        break;
                }
            }
        }
        adapter = new MyAdapter();
        permission_recyclerview.setLayoutManager(new LinearLayoutManager(this));
        permission_recyclerview.setAdapter(adapter);// 提交
    }
    @Override
    protected void onRestart() {
        super.onRestart();
        if(isGotoGetPermission){
            isGotoGetPermission = false;
            setData();
        }
    }
    class MyAdapter extends RecyclerView.Adapter {
        @Override
        public long getItemId(int position) {return position;}
        @Override
        public int getItemCount() {return list.size();}
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new MyAdapter.MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_permission, parent, false));
        }
        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, @SuppressLint("RecyclerView") int position) {
            MyViewHolder v = (MyAdapter.MyViewHolder) holder;
            v.item_permission_name.setText(list.get(position).getName());
            v.item_permission_text.setText(list.get(position).getText());
            if(list.get(position).isIsget()){
                v.item_permission_state.setText("已授权");
                v.item_permission_state.setTextColor(getColor(R.color.blue));
            }else{
                v.item_permission_state.setText("点击授权");
                v.item_permission_state.setTextColor(getColor(R.color.darkgrey));
            }
            v.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(!list.get(position).isIsget()){
                        Uri packageUri = Uri.parse("package:" + getPackageName());
                        switch (position){
                            case 0://悬浮窗
                                Intent intent1 = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, packageUri);
                                intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivityForResult(intent1, 1);
                                isGotoGetPermission = true;
                                break;
                            case 1://应用内安装其他应用
                                Intent intent2 = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageUri);
                                intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivityForResult(intent2, 1);
                                isGotoGetPermission = true;
                                break;
                            case 2://无障碍
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                    //API大于等于26，Android版本在8.0或以上就可以启动
                                    Intent intent3 = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
                                    intent3.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    startActivityForResult(intent3, 1);
                                } else{
                                    //API小于26，Android版本在8.0以下
                                    ToastUtils.Setinfo(getApplicationContext(),"安卓8.0以下暂不支持",2);
                                }
                                isGotoGetPermission = true;
                                break;
                            case 3://读写
                                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
                                    Intent intent4 = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION,packageUri);
                                    intent4.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    startActivityForResult(intent4, 1);
                                }else{
                                    ActivityCompat.requestPermissions(PermissionActivity.this, list.get(position).getPermission(),1);
                                }
                                break;
                            default:
                                ActivityCompat.requestPermissions(PermissionActivity.this, list.get(position).getPermission(),1);
                                break;
                        }
                    }
                }
            });
        }
        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView item_permission_name;
            TextView item_permission_state;
            TextView item_permission_text;
            public MyViewHolder( View itemView) {
                super(itemView);
                item_permission_text = itemView.findViewById(R.id.item_permission_text);
                item_permission_state = itemView.findViewById(R.id.item_permission_state);
                item_permission_name = itemView.findViewById(R.id.item_permission_name);
            }
        }
    }
    @SuppressLint("NotifyDataSetChanged")
    @Override
    public void onRequestPermissionsResult(int requestCode,  String[] permissions,  int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 1){
            boolean isAllGranted = true;
            for(int grant : grantResults){
                if (grant != PackageManager.PERMISSION_GRANTED) {
                    isAllGranted = false;
                    break;
                }
            }
            if (isAllGranted) {
                for(int i = 0 ; i < list.size() ; i++){
                    for(String permission : list.get(i).getPermission()){
                        switch (i){
                            case 0://悬浮窗
                                if(Settings.canDrawOverlays(getApplicationContext())){
                                    list.get(i).setIsget(true);
                                }else{
                                    list.get(i).setIsget(false);
                                }
                                break;
                            case 1://应用内安装其他应用
                                if(getPackageManager().canRequestPackageInstalls()){
                                    list.get(i).setIsget(true);
                                }else{
                                    list.get(i).setIsget(false);
                                }
                                break;
                            case 2://无障碍
                                if(GetUtil.isAccessibilitySettingsOn(getApplicationContext())){
                                    list.get(i).setIsget(true);
                                }else{
                                    list.get(i).setIsget(false);
                                }
                                break;
                            case 3://读写
                                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
                                    if(Environment.isExternalStorageManager()){
                                        list.get(i).setIsget(true);
                                    }else{
                                        list.get(i).setIsget(false);
                                    }
                                }else{
                                    if(ContextCompat.checkSelfPermission(getApplicationContext(), permission) != PackageManager.PERMISSION_GRANTED){
                                        list.get(i).setIsget(false);
                                    }else{
                                        list.get(i).setIsget(true);
                                    }
                                }
                                break;
                            default:
                                if(ContextCompat.checkSelfPermission(getApplicationContext(), permission) != PackageManager.PERMISSION_GRANTED){
                                    list.get(i).setIsget(false);
                                }else{
                                    list.get(i).setIsget(true);
                                }
                                break;
                        }
                    }
                }
                adapter.notifyDataSetChanged();
            }
        }
    }
}